from bottle import static_file, route, run, request
from bottle import jinja2_template as template
import bottle
import os, sys, time
from make_pages import make_page
from spreadsheetdb.uoitpage import make_activity_report
from spreadsheetdb.uoitsmash import make_smash
import json
from datetime import datetime
from pprint import pprint

config = dict(root="../../pages")

@route("/")
def serve_index():
  rootdir = config['root']
  sysaccounts = ['new', 'common', 'template', '.svn']
  accounts = [x for x in os.listdir(rootdir) if not x in sysaccounts]
  return template("spreadsheetdb/templates/index.html", accounts=sorted(accounts))

@route('/live/:name')
def serve_live(name):
  if request.GET.get('load'):
    make_page(config['username'], config['password'], [name], "0.1",
              config['root'])
    return "1"
  else:
    return template("spreadsheetdb/templates/live.html", name=name)

@route('/page/:name')
def serve_page(name):
  return static_file(os.path.join(name, "index.html"), root=config['root'])
  
def activityreport(name, yearstart, monthstart, 
                         yearend, monthend, password=None):
  with open(os.path.join(config['root'], name, 'data.json'), 'r') as f:
    p = json.load(f)
    if yearstart:
      nexturl = os.path.join("/activity-report/", name, str(yearstart))
    else:
      nexturl = os.path.join("/activity-report/", name)

    if request.method == 'GET' and not password:
      # ask for the password
      return template("spreadsheetdb/templates/login.html",
                      name=name, nexturl=nexturl, error=0)
    else:
      # verify the password
      if password:
        userpass = password
      else:
        userpass = request.POST.get('password')
      if userpass == p['information'].get('password'):
        return make_activity_report(p, (yearstart, monthstart), 
                                       (yearend, monthend))
      else:
        return template("spreadsheetdb/templates/login.html",
                        name=name, nexturl=nexturl,
                        error=1)

@route('/activity-report/:name/:year/:pw')
def serve_activity_with_password(name, year, pw):
  if year == 'all':
    y1 = 0; y2 = datetime.now().year+1
  else:
    y1 = int(year); y2 = y1 + 1
  return activityreport(name, y1, 7, y2, 6, password=pw)

@route('/activity-report/:name/:year', method=['GET', 'POST'])
def serve_activityreport_year(name, year):
  return serve_activity_with_password(name, year, None)

@route('/activity-report/:name', method=['GET', 'POST'])
def serve_activityreport_all(name):
  return serve_activity_with_password(name, 'all', None)

@route('/json/:name')
def serve_json(name):
  return static_file(os.path.join(name, "data.json"),
                     root=config['root'])

@route('/common/:filename#.*#')
def server_static(filename):
  return static_file(filename, root=os.path.join(config['root'], 'common'))

@route('/science')
def science1():
  return make_smash(config['username'], config['password'])

@route('/science/:department')
def science2(department):
  return "Science: %s" % department

@route("/slow")
def slow():
  a = time.time()
  time.sleep(5)
  return "Slept %f seconds" % (time.time()-a)

if __name__ == '__main__':
  config['username'] = sys.argv[1]
  config['password'] = sys.argv[2]
  if 'debug' in sys.argv:
    bottle.debug(True)
    run(host="0.0.0.0", port=8000)
  else:
    run(host="0.0.0.0", port=8000, server="cherrypy")
